﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace FBGASaveData
{
    public partial class frmSaveData : Form
    {
        private SaveData _saveData = new SaveData();
        public frmSaveData()
        {
            this.InitializeComponent();
            btnPath.Click+=new EventHandler(btnPath_Click);

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 100;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Enabled = true;
        }
        
        void timer_Tick(object sender, EventArgs e)
        {
            lblStartTime.Text = string.Format("文件开始时间{0}，", CGlobal.dtFileStart);
            lblSaveFileLength.Text=string.Format("已保存{0}字节.",CGlobal.lCurReceiveLength);
        }

        private void btnPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog
            {
                SelectedPath = Environment.CurrentDirectory
            };
            if (DialogResult.OK == dialog.ShowDialog())
            {
                CGlobal.FilePath = dialog.SelectedPath;
                this.txtBoxPath.Text = CGlobal.FilePath;
                if (CGlobal.thMcuRecFromFbg == null)
                {
                    CGlobal.thMcuRecFromFbg = new Thread(new ThreadStart(this._saveData.ReceiveData));
                    CGlobal.thMcuRecFromFbg.Start();
                    CGlobal.thMcuRecFromFbg.IsBackground = true;
                }
            }
        }
    }

    public class SaveData
    {
        private IPAddress CurrentIP
        {
            get 
            {
                IPAddress IPAddr=IPAddress.Parse("10.66.166.5");
                foreach(IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        IPAddr = ip;
                        break;
                    }
                }
                return IPAddr;
            }
        }

        private IPEndPoint ipep = null;
        /// <summary>
        /// 接收数据端口8001，转发数据端口9091
        /// </summary>
        public void ReceiveData()
        {
            while (true)
            {
                try
                {
                    if ((CGlobal.udpFGBAReceive == null) || (this.ipep == null))
                    {
                        CGlobal.udpFGBAReceive = new UdpClient(CGlobal.RecPort);
                        CGlobal.udpFGBAReceive.Client.ReceiveBufferSize = 0xa280;
                        this.ipep = new IPEndPoint(IPAddress.Any, 8001);
                    }
                    if (CGlobal.udpFGBAReceive != null)
                    {
                        byte[] bytes = CGlobal.udpFGBAReceive.Receive(ref this.ipep);
                        this.SaveBuffer(bytes);
                        this.sendData(bytes,9091);
                    }
                }
                catch (Exception exception)
                {
                    System.IO.File.AppendAllText(Application.StartupPath + @"\{0}.log", string.Format("{1}  {2}:{3}\r\n", DateTime.Now.Date,DateTime.Now.ToShortTimeString(), exception.StackTrace, exception.Message));
                }
            }
        }

        private FileStream _fs = null;
        private string curFileName = string.Empty;
        private DateTime _startTime = DateTime.Now;
        /// <summary>
        /// 保存原始光谱到文件
        /// </summary>
        /// <param name="bytes"></param>
        private void SaveBuffer(byte[] bytes)
        {
            try
            {
                if (curFileName == string.Empty)
                {
                    _startTime = DateTime.Now;
                    curFileName = string.Format("{0}.dat", _startTime.ToString("yyyyMMddHHmmss"));
                }
                if (_startTime.AddMinutes(30) <= DateTime.Now)
                {
                    _startTime = DateTime.Now;
                    curFileName = string.Format("{0}.dat", _startTime.ToString("yyyyMMddHHmmss"));
                }
                if (!File.Exists(CGlobal.FilePath + "\\" + curFileName))
                {
                    if (_fs != null)
                    {
                        _fs.Close();
                        _fs.Dispose();
                        _fs = null;
                        CGlobal.lCurReceiveLength = 0;
                    }
                    _fs = File.OpenWrite(CGlobal.FilePath + "\\" + curFileName);
                }
                if (_fs == null)
                {
                    _fs = File.OpenWrite(CGlobal.FilePath + "\\" + curFileName);
                    CGlobal.strCurPath = _fs.Name;
                }
                _fs.Write(bytes, 0, bytes.Length);
                CGlobal.lCurReceiveLength += bytes.LongLength;
                _fs.Flush();
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
        }

        private UdpClient _udpSend = null;
        /// <summary>
        /// 数据转发
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="iSendPort"></param>
        private void sendData(byte[] bytes,int iSendPort)
        {
            try
            {
                if (_udpSend == null && this.ipep!=null)
                {
                    _udpSend = new UdpClient();
                    _udpSend.Connect(this.CurrentIP, iSendPort);
                }
                _udpSend.Send(bytes,bytes.Length);
            }
            catch (Exception ex)
            {
                _udpSend.Close();
                _udpSend = null;
                System.Diagnostics.Debug.WriteLine(ex.StackTrace+":"+ex.Message);
            }
        }
    
    }
}
